import axios from 'axios';
// import saveAs  from 'file-save';
import {saveAs } from 'file-saver';
import {tansParams, blobValidate} from './util';

// 创建axios实例
const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 5000, // 请求超时时间
    headers: {
        token:localStorage.getItem("user-token"),
        "Content-Type": 'application/x-www-form-urlencoded'
    }
})

//添加配置信息
service.interceptors.request.use(function (config) {
    config.headers['version'] = 'v1.0';
    if (localStorage.getItem("user-token")) {
        config.headers['user-token'] = localStorage.getItem("user-token");
    }
    if (localStorage.getItem("access-token")) {
        config.headers['access-token'] = localStorage.getItem('access-token') || '';
    }
    config.headers['plat-form'] = 2;
    return config
}, function (error) {
    return Promise.reject(error)
})



//处理相应结果
service.interceptors.response.use( ({data}) => {
    return Promise.resolve(data)
}, (error) => {
    console.log('err' + error)
    return Promise.reject(error)
})

export const getRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        service({
            method: 'get',
            url,
            params,
        }).then(res => { //axios返回的是一个promise对象
            resolve(res) //resolve在promise执行器内部
        }).catch(err => {
            console.log(err, '异常')
        })

    })
}

//post请求
export const post =(url, param) => {
    return new Promise((resolve, reject) => {
        service({
            method: 'post',
            url,
            data: param,
        }).then(res => {
            resolve(res)
        }).catch(err => {
            console.log(err, '异常')
        })
    })
}

//下载
export const download = (url, params, filename, config) => {
    // downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return service.post(url, params, {
        transformRequest: [(params) => { return tansParams(params) }],
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob',
        ...config
    }).then(async (data) => {
        const isLogin = await blobValidate(data);
        if (isLogin) {
            const blob = new Blob([data], {type: "text/plain;charset=utf-8"})
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            // const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            // Message.error(errMsg);
            console.log(rspObj)
        }
        // downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        // Message.error('下载文件出现错误，请联系管理员！')
        // downloadLoadingInstance.close();
    })
}

// export default {
//     getRequest,
//     post,
//     service,
// }


